import { View, Image } from '@tarojs/components';
import { AtInputNumber, AtButton } from 'taro-ui';
import { useEffect, useState } from 'react';
import Modal from '../Modal';
import Price from '../Price';
import Select from '../Select';
import './index.scss';

interface ISkuItem {
  skuName: string;
  skuId: string | number;
}

export default function ({
  show,
  showNumber = true,
  skuInfo,
  type,
  skuList,
  onChangeSku,
  onCountChange,
  onSubmit,
  onClose = () => {},
}) {
  const [choosed, setChoosed] = useState<ISkuItem | {}>({});
  const [disabled, setDisabled] = useState<boolean>(true);
  const onChange = (skuId) => {
    const filterSku = skuList.filter((item) => item.id === skuId);
    setChoosed(filterSku[0]);
    type !== 'service' ? setDisabled(filterSku[0].number <= 0) : setDisabled(false);
    onChangeSku(filterSku[0]);
  };
  const _onCountChange = (count: number) => {
    onCountChange?.(count);
  };

  useEffect(() => {
    if (skuInfo.id) {
      setChoosed(skuInfo);
      console.log('type', type);
      type !== 'service' ? setDisabled(skuInfo.number <= 0) : setDisabled(false);
    }
  }, [skuInfo, type]);

  return (
    <Modal title="选择规格" show={show} onClose={onClose} className="sku-modal-container2">
      <View className="sku-info">
        <View className="sku-image">
          <Image mode="aspectFit" src={skuInfo.imageUrl} />
        </View>
        <View className="sku-title">
          <View className="sku-name">{skuInfo.goodsName}</View>
          <View className="price-text">
            <Price price={skuInfo.price} />
          </View>
        </View>
      </View>
      <View className="sku-container">
        <View className="sku-item__left">选择规格</View>
        <View className="sku-item__right">
          <Select
            type={type}
            list={skuList.map((sku) => ({ ...sku, value: sku.id }))}
            active={choosed.id}
            onChange={onChange}
          />
        </View>
      </View>
      <View className="choose-sku-title goods-count">
        购买数量
        {show && <AtInputNumber
          type="digit"
          min={1}
          width={40}
          step={1}
          value={skuInfo.count}
          onChange={_onCountChange}
        />}
      </View>
      {showNumber && <View className="sku-number">剩余库存:{skuInfo.number}</View>}
      <View className="bottom-btn">
        <AtButton type="primary" disabled={disabled} onClick={onSubmit}>
          确定
        </AtButton>
      </View>
    </Modal>
  );
}
